package com.example.taobao

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat.startActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import kotlin.concurrent.thread


class sort : AppCompatActivity() {
    private var itemlist: ArrayList<SortItemInfo> = ArrayList<SortItemInfo>()
    private var goodslist: ArrayList<SortgoodsInfo> = ArrayList<SortgoodsInfo>()
    var currentPosition = 0

    val handle = @SuppressLint("HandlerLeak")
    object : Handler()
    {
        override fun handleMessage(msg: Message) {
            goodslist = msg.obj as ArrayList<SortgoodsInfo>
            //使用gridview
            val gridView= findViewById<GridView>(R.id.goods)
            val gdAdapter = PictureAdapter(this@sort,goodslist)
            gridView.adapter = gdAdapter

            //使用Recycler
            val mRecyclerView = findViewById<RecyclerView>(R.id.sort_list)
            val layoutManager = LinearLayoutManager(this@sort)
            mRecyclerView.layoutManager = layoutManager
            val adapter = sortitemAdapter(itemlist)
            mRecyclerView.adapter = adapter
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sort)
        init_list()
        init_goods(currentPosition)
    }

    fun init_list(){
        itemlist.add(SortItemInfo("手机", 0))
        itemlist.add(SortItemInfo("电脑", 1))
        itemlist.add(SortItemInfo("耳机", 2))
        itemlist.add(SortItemInfo("羽绒服", 3))
        itemlist.add(SortItemInfo("毛衣", 4))
        itemlist.add(SortItemInfo("卫衣", 5))
        itemlist.add(SortItemInfo("休闲裤", 6))
        itemlist.add(SortItemInfo("牛仔裤", 7))
        itemlist.add(SortItemInfo("工装裤", 8))
        itemlist.add(SortItemInfo("篮球鞋", 9))
        itemlist.add(SortItemInfo("跑步鞋", 10))
        itemlist.add(SortItemInfo("休闲鞋", 11))


    }

    fun refresh(){
        val gridView= findViewById<GridView>(R.id.goods)
        val gdAdapter = PictureAdapter(this,goodslist)
        gridView.adapter = gdAdapter
    }
    fun init_goods(sort_id:Int){
        goodslist.clear()
        val us = "http://192.168.43.140:8080/aaa_war_exploded/Search_bySort.jsp?id="+sort_id
        thread {
            var url = URL(us)
            val connection = url.openConnection() as HttpURLConnection
            try {
                connection.connectTimeout = 8000
                connection.readTimeout = 8000
                connection.requestMethod = "POST"

                connection.setRequestProperty("Accept-Charset", "UTF-8" )
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
                connection.connectTimeout = 8000
                connection.readTimeout = 8000
                val input = connection.inputStream
                val reader = BufferedReader(InputStreamReader(input) )

                var src : String = ""
                var id : Int = 0
                var name:String = ""
                var i = 0
                val meg :ArrayList<SortgoodsInfo> = ArrayList()
                reader.use {
                    reader.forEachLine {
                        if(it.length > 0) {
                            if( i == 0)
                                id = it.trim().toInt()
                            else if( i == 1)
                                name = it
                            else if(i  == 2)
                                src = it
                            i++
                            if(i == 3){
                                i=0
                                meg.add(SortgoodsInfo(id,name,src))
                            }
                        }
                    }
                }

                goodslist = meg
                val msg = Message()
                msg.obj = meg
                handle.sendMessage(msg)
            } catch (e: Exception )
            {
                e.printStackTrace();
            } finally {
                connection.disconnect()
            }
        }
    }

    inner class sortitemAdapter(private val itemlist: ArrayList<SortItemInfo>) :
        RecyclerView.Adapter<sortitemAdapter.MyViewHolder>() {


        private var ItemClickListenr:ItemClickListenr?=null
        override fun onCreateViewHolder(
            parent: ViewGroup,
            viewType: Int
        ): sortitemAdapter.MyViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(
                R.layout.sort_item,
                parent,
                false
            )
            return MyViewHolder(view)
        }

        fun setOnItemClickLinstenner(listenr: ItemClickListenr){
            this.ItemClickListenr=listenr

        }

        override fun getItemCount(): Int = itemlist.size ?: 0
        override fun onBindViewHolder(holder: sortitemAdapter.MyViewHolder, position: Int) {
            val item = itemlist[position]
            holder.itemname.text=item.itemname
            if(position == currentPosition){
                holder.itemname.setTextColor(Color.parseColor("#b22222"))
                holder.itemView.setBackgroundColor(Color.parseColor("#d3d3d3"))
            }else{
                holder.itemname.setTextColor(Color.parseColor("#000000"))
                holder.itemView.setBackgroundColor(Color.parseColor("#ffffff"))
            }


            holder.itemView.setOnClickListener {
                currentPosition=position
                init_goods(currentPosition)
                refresh()
                notifyDataSetChanged()
            }
        }
        inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            val itemname: TextView = itemView.findViewById(R.id.tv_sort)
        }
    }

    fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        Toast.makeText(this,position, Toast.LENGTH_SHORT).show()
    }

    class PictureAdapter(val content:Context,private val goodslist: ArrayList<SortgoodsInfo>) : BaseAdapter() {
        override fun getCount(): Int {
            return goodslist.size?:0
        }

        override fun getItem(position: Int): Any {
            return goodslist[position]
        }

        override fun getItemId(position: Int): Long {
            return position.toLong()
        }

        override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? {
            val search:String="search"
            var convertView = convertView
            var viewHolder: ViewHolder
            if (convertView == null) {
                viewHolder = ViewHolder()
                // 获得容器
                convertView = LayoutInflater.from(parent.context).inflate(
                    R.layout.sort_goods,
                    parent,
                    false
                )
                // 初始化组件
                viewHolder.image = convertView.findViewById<View>(R.id.sort_goodspic) as ImageView
                viewHolder.title = convertView.findViewById<View>(R.id.sort_goodsname) as TextView
                // 给converHolder附加一个对象
                convertView.tag = viewHolder
            } else {
                // 取得converHolder附加的对象
                viewHolder = convertView.tag as ViewHolder
            }

            // 给组件设置资源
            val goods=goodslist[position]
            //viewHolder.image?.setImageResource(R.drawable.bei)
            viewHolder.image?.let {
                Glide.with(content)
                    .load(goods.goodspic)
                    .into(it)
            }
            viewHolder.title?.text=goods.goodsname
            viewHolder.image?.setOnClickListener {

                val ins = Intent(content, MainDetails::class.java)
                ins.putExtra("id",goodslist[position].goodsid)
                content.startActivity(ins)
                Log.d("search","$position")
            }
            return convertView
        }

        internal inner class ViewHolder {
            var title: TextView? =null
            var image: ImageView? =null
        }


    }

}
